package com.gongj.apppay.utils;

import com.gongj.commons.pojo.User;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class BeanUtil {

    public static Object mapToBean(Map<String, Object> map, Class<?> beanClass) throws Exception {
        Object obj = beanClass.newInstance();
        BeanUtils.populate(obj, map);
        return obj;
    }

    public static <T> Map beanToMap(T obj) {
        BeanMap beanMap = new BeanMap(obj);
        return beanMap;
    }
    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if(obj == null){
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();

        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }

        return map;
    }

    public static void main(String[] args)  throws Exception{
        User user = new User();
        user.setName("sssss");
        Map<String, Object> map = objectToMap(user);
        for (Map.Entry maps : map.entrySet()){
            System.out.println(maps.getKey()  + " ====" + maps.getValue());
        }
    }
}
